package com.trumeen.immichgallery.repository

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking

private val ACCESS_TOKEN = stringPreferencesKey("access_token")
private val REFRESH_TOKEN = stringPreferencesKey("refresh_token")
private val USER_ID = stringPreferencesKey("user_id")
private val IS_AUTHENTICATED = booleanPreferencesKey("is_authenticated")
private val SERVER_ADDRESS = stringPreferencesKey("server_address")

class AuthManager(private val dataStore: DataStore<Preferences>) {

    val isAuthenticatedFlow: Flow<Boolean> = dataStore.data.map { preferences ->
        preferences[IS_AUTHENTICATED] ?: false
    }

    val serverAddressFlow: Flow<String> = dataStore.data.map { preferences ->
        preferences[SERVER_ADDRESS] ?: ""
    }

    fun isAuthenticated(): Boolean = runBlocking {
        dataStore.data.map { it[IS_AUTHENTICATED] == true }.first()
    }

    suspend fun getAccessToken(): String? {
        return dataStore.data.map { it[ACCESS_TOKEN] }.first()
    }

    suspend fun getRefreshToken(): String? {
        return dataStore.data.map { it[REFRESH_TOKEN] }.first()
    }

    suspend fun getUserId(): String? {
        return dataStore.data.map { it[USER_ID] }.first()
    }

    suspend fun getServerAddress(): String {
        return dataStore.data.map { it[SERVER_ADDRESS] ?: "" }.first()
    }

    suspend fun saveAuthState(
        accessToken: String,
        refreshToken: String,
        userId: String,
        serverAddress: String
    ) {
        dataStore.edit { preferences ->
            preferences[ACCESS_TOKEN] = accessToken
            preferences[REFRESH_TOKEN] = refreshToken
            preferences[USER_ID] = userId
            preferences[SERVER_ADDRESS] = serverAddress
            preferences[IS_AUTHENTICATED] = true
        }
    }

    suspend fun clearAuthState() {
        dataStore.edit { preferences ->
            preferences.remove(ACCESS_TOKEN)
            preferences.remove(REFRESH_TOKEN)
            preferences.remove(USER_ID)
            preferences[IS_AUTHENTICATED] = false
        }
    }

    suspend fun updateAccessToken(newToken: String) {
        dataStore.edit { preferences ->
            preferences[ACCESS_TOKEN] = newToken
        }
    }
}